/*
 * @Author: wjk
 * @Date: 2019-11-28 16:31:51
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-25 16:14:34
 * @description: 包含APP内跳转方法, 兼容各端 H5/小程序/hybird交互
 */

// #ifdef H5
import Bridge from '@/plugins/JSBridge'
// #endif
import { routePath, mapWebView, switchTabPage, formatUrlParam } from './tools'
import { couponApi } from '../apis/index'

import store from '@/stores/index'

/* const navigateMap = {
  '/pagesDetail/goods/index': 'goods'
} */
// 需要登录的页面
const needLoginMap = [
  '/pagesBox/box/index',
  '/pages/mine/index',
  '/pages/cart/index',
  '/pages/coupon/index',
  '/pages/strategy/index',
  '/pagesDetail/box/index',
  '/pagesDetail/box-sale/index',
  '/pagesActivity/new-member-ship/index',
  '/pagesActivity/sign-page/index',
  '/pagesActivity/red-packet/index',
  '/pagesMine/order/index',
  '/pagesMine/address/index',
  '/pagesMine/coupon/index',
  '/pagesMine/collection/index',
  '/pagesMaterial/article/detail',
  '/pagesMember/pay/index',
  '/pagesMember/member/index',
  '/pagesMine/myBuddy/list',
  '/pagesActivity/lottery/myAward',
  '/pagesMine/earnings/index',
]

export const h5NeedLoginMap = [
  '/H5/#/activity/signInNewLatest',
  '/H5/#/activity/sign-page-rule',
  '/H5/#/activity/newMemberShip',
  '/H5/#/activity/redPackets',
  '/H5/#/activity/38Execution?showNav=false'
]
/*
 * 函数：页面跳转
 * author: wangzm
 * 参数：url：跳转地址, item：跳转参数， type：跳转类型 navigateTo、reLaunch、redirectTo
 * 返回：void
 */
export const navigateTo = function(url, item = {}, type = 'navigateTo') {
  if (url) {
    const pageUrl = url.split('?')[0]
    // #ifdef H5
    if (Bridge.isInApp) {
      if (pageUrl === '/pages/login/index') {
        const data = {
          type: 'getUser',
          data: { need_login: true }
        }
        console.log('Bridge isInApp', data)
        Bridge.callHandler(data, (res) => {
          if (res) {
            store.SET_USER(JSON.parse(res))
          }
        })
        return
      }
    }
    // #endif
    if (needLoginMap.includes(pageUrl) && !(store && store.state && store.state.token)) {
      console.log('pageAfterLogin', url)
      uni.setStorage({ key: 'pageAfterLogin', data: url })
      navigateTo('/pages/login/index', {}, type === 'redirectTo' ? type : 'navigateTo')
      return
    }

    const h5Path = mapWebView.filter(item => url.includes(item.url))
    if (h5Path.length > 0) {
      h5NavigateTo(url, type)
    } else {
      /* eslint-disable */
      const page = getCurrentPages()
      /* eslint-disable-end */
      if (type === 'navigateTo' && page.length >= 10) {
        uni.reLaunch({ url })
      }
      if (switchTabPage.includes(url)){
        uni.switchTab({
          url: url
        })
      } else {
        uni[type]({ url })
      }
    }
  }
}


/**
 * 获取连接url各部分
 * @param {*} url 
 * @param {*} type 
 */
function getUrlHost(url){
  if (url.indexOf('//') !== -1){
    const arr1 = url.split('//')
    const firtSep = arr1[1].indexOf('/')
    if (firtSep !== -1){
      const host = arr1[1].substring(0,firtSep)
      return arr1[0] + '//' + host
    } else {
      return arr1[0] + '//' + arr1[1]
    }
  } else {
    return url
  }
}
/*
 * H5页面跳转
 * author: zlf
 * 参数：url：跳转地址
 * 返回：void
 */

export const h5NavigateTo = function(url, type = 'navigateTo') {
  if (!url||url==='null'){
    return
  }
  const appPath = routePath.filter(item => url.indexOf(item) >= 0)
  if (url.indexOf('/detail/activity') >= 0){
    if (appPath.length === 0) {
      appPath.push('/pagesDetail/template/index')
    }
  }
  if (appPath.length > 0) {
    let newUrl = appPath[0]
    if (url.indexOf('?') >= 0) {
      newUrl += url.substring(url.indexOf('?'))
    }
    /* eslint-disable */
    const page = getCurrentPages()
    /* eslint-disable-end */
    const currentPage = page[page.length - 1].route
    // 判断是否是当前页
    if (newUrl.indexOf(currentPage) === -1) {
      if (switchTabPage.includes(appPath[0])){
        navigateTo(newUrl, {}, 'switchTab')
      } else {
        navigateTo(newUrl, {}, type)
      }
    }
  } else {
    // const webPath = mapWebView.filter(item => url.indexOf(item.url) >= 0)
    const hostName = getUrlHost(url)
    uni.setStorageSync('webViewKey', hostName)
    let params = url.replace(hostName, '')
    if(h5NeedLoginMap.includes(params)&& !(store && store.state && store.state.token)) {
      uni.setStorage({ key: 'pageAfterLogin', data: url })
      navigateTo('/pages/login/index')
      return
    } else {
      let reg=/^\//;
      if(reg.test(url)){
        navigateTo(url,{}, type);
        return;
      }
      // #ifdef H5
      location.href = url
      // #endif
      // #ifndef H5
      navigateTo(`/pages/webview/index?params=${encodeURIComponent(params)}`,{}, type)
      // #endif
    } 
  }
}
/**
 * 返回操作
 */
export function pageNavigateBack() {
  const pages = getCurrentPages()
  if (pages.length <= 1){
    toMpHomePage()
    return
  }
  uni.navigateBack()
}

export function pageAfterLogin(_this) {
  uni.getStorage({
    key: 'pageAfterLogin',
    success: async({data}) => {
      console.log('getStoragePageAfterLogin', data)
      if (data){
        if (data.pageType){
          if (data.pageType === 'newMember'){
            const resNew = await _this.$api.excellentApi.isNewUser()
            if (resNew.success && resNew.data) {
              navigateTo(res.data, {}, 'redirectTo')
              uni.removeStorage({ key: 'pageAfterLogin' })
            } else {
              pageNavigateBack()
            }
          } else {
            navigateTo(data.page, {}, 'redirectTo')
            uni.removeStorage({ key: 'pageAfterLogin' })
          }
        } else {
          navigateTo(data, {}, 'redirectTo')
          uni.removeStorage({ key: 'pageAfterLogin' })
        }
      }

      // if (res.data && res.data.match('/pagesDetail/box/index')) { // 跳【箱起】页
      //   uni.removeStorage({
      //     key: 'pageAfterLogin',
      //     success: () => {
      //       uni.switchTab({
      //         url: '/pages/home/index'
      //       })
      //       uni.$emit('toBoxPage', '2')
      //     },
      //     fail: () => {
      //       uni.switchTab({
      //         url: '/pages/home/index'
      //       })
      //       uni.$emit('toBoxPage', '2')
      //     }
      //   });
      // } else if (res.data.indexOf('/pagesActivity/new-member-ship/index') > -1) {
      //   const resNew = await _this.$api.excellentApi.isNewUser()
      //   if (resNew.success && resNew.data) {
      //     navigateTo(res.data, {}, 'redirectTo')
      //     uni.removeStorage({ key: 'pageAfterLogin' })
      //   } else {
      //     pageNavigateBack()
      //   }
      // } else {
      //   navigateTo(res.data, {}, 'redirectTo')
      //   uni.removeStorage({ key: 'pageAfterLogin' })
      // }
    },
    fail: () => {
      console.log('fail')
      pageNavigateBack()
    }
  }) 
}


/**
 * 绑定邀请码
 * @param {} _this 
 */
export async function bindInviteCode(_this, data={}, callBack=null){
  const dataCode = uni.getStorageSync('share_code')
  if (dataCode) {
    const user = data.user
    
    if (!(user && !user.referral_code && user.current_member_card_type < 3)) {
      pageAfterLogin(_this)
      return
    }
    let bind_channel = '2'
    // #ifdef H5
    bind_channel = '1'
    // #endif
    const res = await _this.$api.mineApi.bindInviteCode({
      invite_code: dataCode,
      bind_channel: bind_channel // 1: 通过H5分享邀请码
    })
    if (res.success) {
      // uni.removeStorageSync('share_code') // 还是不能清楚，不然新用户下单的时候就没有码绑定了
      pageAfterLogin(_this)
    } else {
      setTimeout(() => {
        pageAfterLogin(_this)
      }, 2000)
    }
  } else {
    if (data.is_first_login) {
      _this.$navigateTo('/pages/login/bind', {}, 'redirectTo')
      return
    }
    pageAfterLogin(_this)
  }
}

function urlParams(url) {
  const params = {}
  let h
  const hash = url.slice(url.indexOf('?') + 1).split('&')
  for (var i = 0; i < hash.length; i++) {
    h = hash[i].split('=') //
    params[h[0]] = h[1]
  }
  return params
}

/**
 * @Author: wangzm
 * @description: 跳转到首页
 */
export function toMpHomePage() {
  // #ifdef H5
  if(Bridge.isInApp){
    Bridge.callHandler({
      type: 'nativeLink',
      data: 'Home'
    })
    return
  }
  // #endif
  navigateTo(`/pages/home/index`, {}, 'reLaunch')
}

/**
 * @Author: wangzm
 * @description: 返回上一页
 */
export function toBackPage(step, type) {
  // #ifdef H5
  if(Bridge.isInApp){
    Bridge.callHandler({
      type: 'returnButtonClick',
      data: {
        type: type || 'return'
      }
    })
    return
  }
  // #endif
  const pages = getCurrentPages()
  if (pages.length <= 1){
    toMpHomePage()
    return
  }
  uni.navigateBack({ delta: step || 1 })
}

/**
 * @Author: wjk
 * @Date: 2019-11-28 16:33:49
 * @LastEditors: wjk
 * @description: 跳转到订单详情
 * @param {item} 订单实例
 * @return: 跳转结果
 */
export function toOrderDetail(item) {
  navigateTo(`/pagesMine/order/detail?orderNo=${item.orderNo}`)
  return true
}
/**
 * @Author: zlf
 * @Date: 2019-11-28 16:33:49
 * @LastEditors: zlf
 * @description: 跳转到商品详情
 * @param {item} 商品箱起
 * @return: 跳转结果
 */
export function toGoodsDetail(item) {
  navigateTo(`/pagesDetail/goods/index?goodsId=${item.goodsId}`)
}

/**
 * @Author: wjk
 * @Date: 2020-01-08 13:26:58
 * @LastEditors: wjk
 * @description: 
 * @param {item} 跳转实例
 * @param {item.type} 跳转类型 // 类型，0 h5，1商品，2套餐，201组合套餐,3专题详情;4专题列表;5活动;6碧选优品;7商品分类;8直播;9箱起;10拼团 33:箱起活动,34箱起礼包 78 箱起列表 79: 箱起详情
 * 12碧划算
 * 13淘宝官方活动
 * 14团油
 * 15今日热卖
 * 16抽奖
 * 30免费领
 * 31低价购
 * 33箱起活动
 * 34箱起礼包
 * 35箱起商品
 * 36箱起首页
 * 37我的箱起
 * 38碧选首页
 * 39签到
 * 40我的好友
 * 41会员中心
 * 42vip支付页
 * 43钻石支付页
 * 51碧选直播小程序
 * @param {collection} 埋点信息
 * @return: 跳转结果
 */
export async function toFunctionDetail(item, type = 'navigateTo', collection = {}) {
  console.log('toFunctionDetail', item);
  console.log(Number(item.type));
  let need_login_id=[40,41,42,43];//app端需要登陆的id
  let temp = '';
  // const singleTypes = [7, 9, 10, 12, 15, 50, 51,35,36,37]
  // if (!item.type_val && !singleTypes.includes(Number(item.type))) {
  //   return
  // }
  // #ifdef H5
  if(Bridge.isInApp){
    if(need_login_id.includes(Number(item.type))){
      const data = {
        type: 'getUser',
        data: { need_login: true }
      }
      Bridge.callHandler(data, (res) => {
        if (res) {
          store.SET_USER(JSON.parse(res))
        }
      })
    }
    if (Number(item.type) === 35) { // type为35跳箱起商品
      Bridge.callHandler({
        type: 'boxGoods',
        data: {
          id:item.boxId
        }
      })
    }
    else if (Number(item.type) === 36) { // type为36跳箱起首页
      Bridge.callHandler({
        type: 'homeBox'
      })
    } else if (Number(item.type) === 37) { // type为37跳我的箱起
      Bridge.callHandler({
        type: 'mybox'
      })
    }
    else if (Number(item.type) === 38) { // 跳转首页
      Bridge.callHandler({
        type: 'nativeLink',
        data: 'Home'
      })
    }
    else if (Number(item.type) === 40) { // 我的好友
      Bridge.callHandler({
        type: 'MyFriends'
      })
    }
    else if (Number(item.type) === 41) { // 会员中心
      Bridge.callHandler({
        type: 'MemberCenter'
      })
    }
    else if (Number(item.type) === 42) { // vip支付页
      Bridge.callHandler({
        type: 'MemberPay',
        data:{
          memberKey:'vip'
        }
      })
    }
    else if (Number(item.type) === 43) { // 钻石支付页
      Bridge.callHandler({
        type: 'MemberPay',
        data:{
          memberKey:'diamond'
        }
      })
    }
    else if(Number(item.type) === 88){//碧划算商品
      Bridge.callHandler({
        type: 'bhsGoods',
        data: item
      })
    } else {
      Bridge.callHandler({
        type: 'multi',
        data: item
      })
    }
    return
  }
  // #endif
  if(collection.preseat) {
    uni.setStorage({
      key: 'preseat',
      data: collection.preseat
    })
  }
  if(collection.firstseat) {
    uni.setStorage({
      key: 'firstseat',
      data: collection.firstseat
    })
  }
  if (item.name === '碧家精选') {
    navigateTo('/pagesDetail/choiceness/index?title=碧家精选', {}, type)
    return
  }
  const type_val = item.type_val?decodeURIComponent(item.type_val):'';
  if(item.type===''||item.undefined||item.type===null){
    return;
  }
  switch (Number(item.type)) {
    case 9:
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
    case 78:
    case 79:
      // H5，小程序端暂时不跳箱起
      uni.showToast({
        title: '暂时仅支持APP查看，请下载APP',
        duration: 2000,
        icon: 'none'
      })
      return
      break;
    case 0:
    case 21:
      // #ifdef MP-WEIXIN
      if (type_val.indexOf('/activity/wholeFilms') > -1) {
        uni.showModal({
          title: '温馨提示',
          content: '请前往‘碧选’公众号，查看更多内容',
          showCancel: false
        })
        return
      }
      // #endif
      if (type_val.indexOf('/detail/activity?') > -1 || type_val.indexOf('/pagesDetail/template/index') > -1) {
        const query = item.type_val.split('?')[1]
        const queryArr = query.split('&')
        const obj = []
        queryArr.forEach(function(item) {
          var value = item.split('=')[1]
          var key = item.split('=')[0]
          obj[key] = value
        })
        navigateTo(`/pagesDetail/template/index?id=${obj.id}`)
      } else if (type_val.indexOf('/detail/goods?') > -1 || type_val.indexOf('/pagesDetail/commodity/index') > -1) {
        const query = type_val.split('?')[1]
        navigateTo(`/pagesDetail/commodity/index?${query}`, {}, type)
      } else if(type_val.indexOf('/activity/sign-page-rule')>-1 || type_val.indexOf('/pagesMine/my-red-packets/index')>-1) {
        navigateTo(`/pagesMine/my-red-packets/index`, {}, type)
      } else if(type_val.indexOf('/mine/coupon')>-1 || type_val.indexOf('/pagesMine/coupon/index')>-1) {
        navigateTo(`/pagesMine/coupon/index`, {}, type)
      } else if (type_val.indexOf('/activity/newMemberShip') > -1 || type_val.indexOf('/pagesActivity/new-member-ship/index') > -1) {
        const query = type_val.indexOf('?') > -1 ? ('?'+type_val.split('?')[1]) : ''
        navigateTo(`/pagesActivity/new-member-ship/index${query}`, {}, type)
      } else if (type_val.indexOf('/activity/signInNewLatest') > -1 || type_val.indexOf('/pagesActivity/sign-page/index') > -1) {
        navigateTo('/pagesActivity/sign-page/index', {}, type)
      } else if (type_val.indexOf('/pagesActivity/red-packet/index') > -1) {
        const query = type_val.indexOf('?') > -1 ? ('?'+type_val.split('?')[1]) : ''
        navigateTo(`/pagesActivity/red-packet/index${query}`, {}, type)
      } else {
        if(type_val){
          h5NavigateTo(type_val, type)
        }
      }
      break
    case 1:
    case 2:
      navigateTo(`/pagesDetail/commodity/index?id=${encodeURIComponent(type_val)}&from_type=${item.from_type}&activity_id=${item.activity_id || ''}&goods_type=${item.type}&pack_type=${item.pack_type}`, {}, type)
      break
    case 3: // 爆款推荐、限时秒杀
      navigateTo(`/pagesDetail/recommend/index?tag=${encodeURIComponent(type_val)}&title=${item.name}`, {}, type)
      break
    case 4:
      navigateTo('/pagesDetail/choiceness/index?title=' + item.name, {}, type)
      // navigateTo(`/pagesDetail/recommend/index?id=${encodeURIComponent(type_val)}`, {}, type)
      break
    case 5:
      navigateTo(`/pagesDetail/recommend/index?id=${encodeURIComponent(type_val)}`, {}, type)
      break
    case 6:
      uni.showToast({
        title: '敬请期待!',
        icon: 'none'
      })
      // navigateTo(`/pagesDetail/excellent/index?id=${encodeURIComponent(type_val)}`, {}, type)
      break
    case 7: // 商品分类
      navigateTo(`/pagesDetail/schema/index?title=${encodeURIComponent(item.name)}`, {}, type)
      break
    case 8: // 直播
    case 51:
      // #ifdef MP-WEIXIN
      let token = ''
      if (store && store.state && store.state.token) {
        token = store.state.token
      }
      let path = '/pagesDetail/living-list/index'
      if (item.type_val) {
        path = item.type_val
      }
      if (Number(item.type) === 8) {
        path = '/pagesDetail/living-list/index'
      }
      navigateToMiniProgram({
        extraData: {
          toPath: path,
          platform: 'minProgram-bx'
        },
        success: () => {
          store.dispatch('setExtraData', null)
        },
        fail: (err) => {
          console.log(err)
        }
      })
      // #endif
      // #ifdef H5
      uni.showToast({
        title: '敬请期待!',
        icon: 'none'
      })
      // #endif
      // navigateTo(`/pagesActivity/live-telecast/index?title=${encodeURIComponent(item.name)}`, {}, type)
      break
    case 9: // 箱起
      if (store && store.state && store.state.token){
        uni.removeStorage({
          key: 'pageAfterLogin',
          complete: () => {
            navigateTo('/pagesBox/box/index')
          }
        });
        
      } else {
        navigateTo('/pagesBox/box/index')
        // navigateTo(`/pagesDetail/box/index?title=${encodeURIComponent(item.name)}`, {}, type)
      }
      break
    case 10: // 拼团
      navigateTo(`/pagesActivity/group-buy/index`, {}, type)
      // navigateTo(`/pagesActivity/group-buy/index?title=${encodeURIComponent(item.name)}`, {}, type)
      break
    case 12:
      navigateTo('/pages/coupon/index', {}, 'switchTab') // 碧划算
      break
    case 13:
      uni.showToast({
        title: '请下载碧选App ，去跳转淘宝活动!',
        icon: 'none'
      })
      break
    case 14: // 团油
      uni.showToast({
        title: '请下载碧选App来体验能购物返利的碧划算功能',
        icon: 'none',
        duration:3000
      })
      break
    case 15: // 今日热卖
      navigateTo(`/pagesActivity/hot-buy/index`, {}, type)
      break
    case 16: // 抽奖
      navigateTo(`/pagesActivity/lottery/sudoku`, {}, type)
      break
    case 30: // 免费领
    case 31: // 低价购
      navigateTo(`/pagesMember/discount/index?type=${item.type}&memberCardType=${item.memberCardType}`, {})
      break
    case 33: // 箱起活动
      temp = {
        from_type: item.from_type,
        series_id: encodeURIComponent(type_val),
        box_id: item.boxGoodsDTOS ? item.boxGoodsDTOS[0].boxId : '',
        type: 'boxGoods'
      }
      navigateTo(formatUrlParam('/pagesDetail/commodity/index', temp), {}, type)
      break
    case 34: // 箱起礼包
      navigateTo(`/pagesDetail/commodity/index?bonus_gift_id=${type_val}&type=boxGoods`, {}, type)
      break
    case 38: // 首页
      navigateTo('/pages/home/index', {})
      break
    case 39: // 签到
      navigateTo('/pagesActivity/sign-page/index');
      break
    case 40: // 我的好友
      navigateTo('/pagesMine/myBuddy/list');
      break
    case 41: // 会员中心
      navigateTo('/pagesMember/member/index');
      break
    case 42: // vip支付页
      navigateTo('/pagesMember/pay/index?type=vip');
      break
    case 43: // 钻石支付页
      navigateTo('/pagesMember/pay/index?type=diamond');
      break
    case 50:
      let newPath =  type_val
      if (!newPath) {
        newPath = '/pages/home/index'
      }
      const type = newPath.match('/pages/home/index') || newPath.match('/pages/coupon/index') || newPath.match('/pages/moments/index') || newPath.match('/pages/mine/index') ? 'switchTab' : 'navigateTo'
      navigateTo(newPath, {}, type)
      break
    case 77: // 优惠券
      if (store && store.state && store.state.token){
        const pType = {
          'h5': 'BIXUAN_H5',
          'mp-weixin': 'BIXUAN_MINI'
        }
        const res = await couponApi.receiveCoupon({
          coupon_activity_id: item.type_val,
          fromPath: 'GOODS_DETAIL',
          platform: pType[process.env.VUE_APP_PLATFORM]
        })
        if (res.success) {
          uni.showToast({
            title: '领取成功, 请到我的-优惠券中心查看',
            icon: 'none'
          })
        }
      } else {
        navigateTo('/pages/login/index', {}, type)
      }
      break
    case 79: // 箱起活动
      temp = JSON.parse(type_val)
      temp.type = 'boxGoods'
      navigateTo(formatUrlParam('/pagesDetail/commodity/index', temp), {}, type)
      break
    case 88: //碧划算商品
        uni.showToast({
          title: '前往碧选APP，查看详情',
          icon: 'none',
          duration: 3000
        })
        break
    case 201:
      navigateTo(`/pagesDetail/commodity/index?id=${encodeURIComponent(type_val)}&from_type=${item.from_type}&activity_id=${item.activity_id || ''}&goods_type=4&pack_type=${item.pack_type}`, {}, type)
      break
    default:
      break
  }
  // if (collection.pre_page) {
  //   vue.$store.dispatch('setPrePage', collection.pre_page)
  // }
}

/**
 * @Author: zlf
 * @Date: 2020-01-08 13:26:58
 * @LastEditors: wjk
 * @description: 
 * @param {item} 跳转实例
 * @param {item.type} 跳转类型 // 类型，0 h5，1商品，2套餐，3专题详情;4专题列表;5活动;6碧选优品;7商品分类;8直播;9箱起;10拼团 33:箱起活动 78 箱起列表 79: 箱起详情 88碧划算商品
 * 35单个箱起商品
 * @param {collection} 埋点信息
 * @return: 跳转结果
*/
// from_type String	来源1：单品@2：秒杀@3：套餐@4：预售@5：专题|@6：活动||@7：兰密@8：大区@9城市合伙人@10买赠赠品@11箱起@12箱起赠品
export function toGoods(item, type = 'navigateTo', collection = {}) {
  if (!item.type_val) {
    item.type_val = item.goods_id
  }
  // #ifdef H5
  if(Bridge.isInApp){
    if(Number(item.type) === 88){
      Bridge.callHandler({
        type: 'bhsGoods',
        data: item
      })
    }else if(Number(item.type) === 35){//跳转原生箱起商品详情
      Bridge.callHandler({
        type: 'boxGoods',
        data: {
          id:item.boxId
        }
      })
    }else {
      Bridge.callHandler({
        type: 'goods',
        data: item
      })
    }
    return
  }
  // #endif
  if(item.type === 35){//跳转箱起前端商品详情,暂不启用
    uni.showToast({
      title: '暂时仅支持APP查看，请下载APP',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if(item.type === 88){ // 碧划算商品
    toFunctionDetail(item)
    return
  }
  const pages = getCurrentPages()
  const currentPage = pages[pages.length-1]

  if(collection.preseat) {
    uni.setStorage({
      key: 'preseat',
      data: collection.preseat
    })
  }
  if(collection.firstseat) {
    uni.setStorage({
      key: 'firstseat',
      data: collection.firstseat
    })
  }

  const query = {
    id: item.goods_id,
    from_type: item.from_type,
    activity_id: item.activity_id,
    goods_id: item.goods_id,
    goods_type: item.goods_type || item.type,
    promote: item.promotion,
    pack_type: item.pack_type
  }
  // 判断是否带邀请码， 幼儿园比赛用 kinder
  if (item.inviteCode) {
    query.inviteCode = item.inviteCode
  }
  if (item.invite_code) {
    query.invite_code = item.invite_code
  }
  
  if (item.end_time && item.date) {
    query.end_time = item.end_time
    query.date = item.date
  }

  if (item.group_buying_id) {
    query.group_buying_id = item.group_buying_id
  }
  // 判断是否3800 箱起礼包
  if (item.bonus_gift_id) {
    query.bonus_gift_id = item.bonus_gift_id
  }
  const url = formatUrlParam('/pagesDetail/commodity/index', query)
  navigateTo(url, {}, type)
}


/**
 * 跳转另外的小程序
 * @param {*} 
 * options = {
 *  appId: "",  // 要打开的小程序 appId
    path: '',  // 也可以拼接参数
    extraData: {}, //需要传递给目标小程序的数据，目标小程序可在 App.vue 的 onLaunch或onShow 中获取到这份数据。
    envVersion: '',  // 打开的小程序版本，有效值： develop（开发版），trial（体验版），release（正式版）
    success: () => {},
    fail: () => {}
 * } 
 */

export function navigateToMiniProgram(options){
  const envVersion = {
    'TEST': 'develop', 
    'UAT': 'trial', 
    'PROD': 'release'
  }
  const defaultOptions = {
    appId: 'wxcd7c4574c80dfaa8',  // 碧直播的appid
    path: 'pages/middle/index',
    extraData: {},
    envVersion: envVersion[process.env.VUE_APP_BUILD_TYPE] || 'release', 
    success: () => {
      store.dispatch('setExtraData', null)
    },
    fail: () => {}
  }
  const obj = Object.assign({}, defaultOptions, options)
  if (obj.extraData) {
    obj.extraData.token =  obj.extraData.token || (store && store.state && store.state.token) || ''
    obj.extraData.share_code = obj.extraData.share_code ||  uni.getStorageSync('share_code') || ''
    obj.extraData.platform = obj.extraData.platform || 'minProgram-bx'
    obj.extraData.hasBack = true
  }
  console.log(obj)
  if (store &&  store.state && store.state.extraData && store.state.extraData.hasBack ) {
    navigateBackMiniProgram({
      extraData:{
        ...obj.extraData,
        hasBack: false
      },
      success: obj.success,
      fail: obj.fail
    })
    return
  }
  if (!obj.appId){
    uni.showToast({
      title: '请填写appId'
    })
    return
  }
  uni.navigateToMiniProgram(obj)
}
/**
 * 返回到上一个小程序 前提是必须有
 * @param {*} 
 * options = {
    extraData: {}, //需要传递给目标小程序的数据，目标小程序可在 App.vue 的 onLaunch或onShow 中获取到这份数据。
 * } 
 */
export function navigateBackMiniProgram(options){
  const defaultOptions = {
    extraData: {},
    success: () => {},
    fail: () => {}
  }
  const obj = Object.assign({}, defaultOptions, options)
  console.log(obj)
  uni.navigateBackMiniProgram(obj)
}